package com.site.core.translate;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.NameValuePair;

import com.cnc.bas.util.Log;
import com.site.common.Language;
import com.site.util.HttpUtil;

/**
 * bing 翻译API
 * @author Administrator
 *
 */
public class BingTranslate  {
	
	protected static Log  log = Log.getLogger(BingTranslate.class);
	
	// api接口地址
	protected static String baseUrl = "http://api.microsofttranslator.com/V2/HTTP.svc/";
	
	// AppId
	private static String APPID = "08CF952D4651D83FC1B11F1E409A3918BE350422";
	
	// 语言映射Map<systemLang, bingLang>
	private static Map<String, String> map = new HashMap<String, String>();
	
	private static final String CHINESE_SIMPLIFIED = "zh-CHS";
	private static final String ENGLISH = "en";
	private static final String SPANISH = "es";
	private static final String PORTUGUESE = "pt";
	private static final String JAPANESE = "ja";
	private static final String GERMAN = "de";
	private static final String FRENCH = "fr";

	static{
		init();
	}
	
	private static void init(){
		map.put(Language.CHINESE_SIMPLIFIED, CHINESE_SIMPLIFIED);
		map.put(Language.ENGLISH, ENGLISH);
		map.put(Language.SPANISH, SPANISH);
		map.put(Language.PORTUGUESE, PORTUGUESE);
		map.put(Language.JAPANESE, JAPANESE);
		map.put(Language.GERMAN, GERMAN);
		map.put(Language.FRENCH, FRENCH);
	}
 
	/**
	 * 翻译
	 */
	public String translate(String content, String fromLang, String toLang) {
        String url = baseUrl + "Translate";
        NameValuePair[] pairs = new NameValuePair[4];
        pairs[0] = new NameValuePair("appId", APPID);
        pairs[1] = new NameValuePair("from", map.get(fromLang));
        pairs[2] = new NameValuePair("to", map.get(toLang));
        pairs[3] = new NameValuePair("text", content);
        
        for(int i=0; i<3; i++){
        	try{
                String result = HttpUtil.doGet(url, pairs);
                String beginStr = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">";
                int begin = result.indexOf(beginStr);
                int end = result.lastIndexOf("</string>");
                result = result.substring(begin+beginStr.length(), end);
                return result;
            }
            catch (Exception e){
            	log.logError("translate exception:" + e.getMessage());
            }
            try{
            	Thread.sleep(3000);
            }
            catch(Exception e){
            }
        }
        
		return null;
	}

}
